package com.stsdai.sso.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stsdai.manager.mapper.ShopMapper;
import com.stsdai.manager.pojo.Shop;
import com.stsdai.manager.pojo.User;
import com.stsdai.sso.redis.RedisUtils;
import com.stsdai.sso.service.ShopService;
import com.stsdai.sso.service.UserService;

@Service
public class ShopServiceImpl implements ShopService {

	@Autowired
	private UserService userService;

	@Autowired
	private ShopMapper shopMapper;

	@Autowired
	private RedisUtils redisUtils;

	private static final ObjectMapper MAPPER = new ObjectMapper();

	@Value("${STSDAI_SHOP_TICKET_KEY}")
	String STSDAI_SHOP_TICKET_KEY;

	@Override
	public Shop queryShopByTicket(String ticket) {
		// TODO Auto-generated method stub
		User user = userService.queryUserByTicket(ticket);
		if (user != null) {
			// 设置查询条件
			Shop shop = new Shop();
			shop.setId(user.getId());
			Shop result = shopMapper.selectOne(shop);
			if (result != null) {

			}
		}

		return null;
	}

	@Override
	public void doShopRegister(Shop shop) {

		// 设置用户数据
		shop.setCreated(new Date());
		shop.setUpdated(shop.getCreated());
		shop.setStatus(0);
		this.shopMapper.insert(shop);
	}

	@Override
	public String doLoginShop(Long shopId) {
		//封装查询条件
		Shop shop = new Shop();
		shop.setId(shopId);
		// 根据shopId查询是否有卖家信息
		Shop result = this.shopMapper.selectOne(shop);
		// 判断查询结果是否为空
		if (result != null) {
			// 如果为非空，表示卖家登录成功，生成唯一的key，就是shop_ticket
			// 可以利用redis单线程的特点，再加上incr每次加一，获取唯一数
			// 使用redis获取的唯一数，加上用户id拼接唯一数
			int status = result.getStatus();
			String shopTicket = null;
			//如果卖家信息已通过验证
			if(status == 1){
				shopTicket = "" + this.redisUtils.incr("STSDAI_SHOP_TICKET_KEY") + result.getId();
				// 存入redis
				try {
					this.redisUtils.set(this.STSDAI_SHOP_TICKET_KEY + shopTicket, MAPPER.writeValueAsString(result),
							60 * 60);
				} catch (JsonProcessingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			//如果卖家信息未通过验证
			}else if(status == 0){
				shopTicket = "0";
			}
			// 返回数据
			return shopTicket;

		}
		// 如果登录失败，或者有异常，返回null
		return null;
	}

}
